package com.moter.demo01.rpc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * 可以接受多个客户端，但是消耗太多资源，不断在内核和程序之间来回查看是否有新的客户端连接和或者消息
 */
public class SocketNIO {
    public static void main(String[] args) throws Exception{
        LinkedList<SocketChannel> channels = new LinkedList<>();//保存client宿主
        ServerSocketChannel channel = ServerSocketChannel.open();//开辟一个通道
        channel.bind(new InetSocketAddress(9090));//设置端口号
        channel.configureBlocking(false);//设置为非阻塞
        while(true){
            TimeUnit.SECONDS.sleep(1);
            SocketChannel accept = channel.accept();//不会阻塞
            if(accept==null){
                System.out.println("没有客户端发请求");
            }else{
                accept.configureBlocking(false);
                channels.add(accept);
                System.out.println("接受到请求 来自："+accept.socket().getPort());
            }
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
            for (SocketChannel client : channels) {
                int read = client.read(byteBuffer);//这里也不会阻塞（NIO）  BIO会阻塞
                if(read>0){
                    byteBuffer.flip();//读取数据， 增加一个limit指针，指向数据末端。
                    byte[] data = new byte[byteBuffer.limit()];
                    byteBuffer.get(data);//读取position到limit里面的东西
                    String msg = new String(data);
                    System.out.println(msg);
                    byteBuffer.clear();//清除所有数据
                }
            }
        }



    }
}
